package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"new_house/api/request"
	"new_house/internal/dao"
	"new_house/internal/model"
	"time"
)

func AddAppointment(c *gin.Context) {
	var req request.AddAppointmentReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code":    10000,
			"message": "参数错误",
			"data":    nil,
		})
		return
	}
	var user model.User
	dao.GetOneById(c.GetUint("userId"), &user)
	if !(user.UType == 1) {
		c.JSON(200, gin.H{
			"code":    10000,
			"message": "该用户无权限预约看房",
			"data":    nil,
		})
		return
	}
	var house model.House
	dao.GetOneById(req.HouseId, &house)
	if house.Id == 0 {
		c.JSON(200, gin.H{
			"code":    10000,
			"message": "您要预约的房源不存在",
			"data":    nil,
		})
		return
	}
	parse, _ := time.Parse(time.DateTime, req.AppointTime)
	if time.Now().Unix() > parse.Unix() {
		c.JSON(200, gin.H{
			"code":    10000,
			"message": "当前时间已过预约时间",
			"data":    nil,
		})
		return
	}
	result := dao.Create(&model.Appointment{
		UserId:      c.GetUint("userId"),
		HouseId:     req.HouseId,
		AppointTime: parse,
	})
	if !result {
		c.JSON(200, gin.H{
			"code":    10000,
			"message": "预约看房失败",
			"data":    false,
		})
		return
	}
	c.JSON(200, gin.H{
		"code":    http.StatusOK,
		"message": "预约看房成功",
		"data":    true,
	})
}

func RemoveAppointment(c *gin.Context) {
	var req request.RemoveAppointmentReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code":    10000,
			"message": "参数错误",
			"data":    nil,
		})
		return
	}
	var user model.User
	dao.GetOneById(c.GetUint("userId"), &user)
	if !(user.UType == 1) {
		c.JSON(200, gin.H{
			"code":    10000,
			"message": "该用户无权限取消预约看房",
			"data":    nil,
		})
		return
	}
	result := dao.Delete(&model.Appointment{
		Id: req.Id,
	})
	if !result {
		c.JSON(200, gin.H{
			"code":    10000,
			"message": "取消预约看房失败",
			"data":    false,
		})
		return
	}
	c.JSON(200, gin.H{
		"code":    http.StatusOK,
		"message": "取消预约看房成功",
		"data":    true,
	})
}
